Event delegation is a technique in JavaScript where you attach a single event listener to a parent element instead of multiple event listeners to individual child elements. The parent element listens for events triggered by its child elements and responds accordingly.
In event delegation, the parent element listens for events on its children through event bubbling. When an event is triggered on a child element, it "bubbles" up the DOM tree to the parent. The parent can then check if the event target matches the desired child element and handle it.
document.querySelector("#parent").addEventListener("click", function(event) {
if (event.target && event.target.matches("button")) {
console.log("Button clicked:", event.target.textContent);
}
});
Output: Logs the button text when a button inside the parent container is clicked.
Event delegation is a powerful and efficient technique for handling events in JavaScript, especially when dealing with dynamic content or large sets of elements. It simplifies event management and enhances performance by minimizing the number of event listeners attached to individual elements.